﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace FileSysExp.Core
{
    [StructLayout(LayoutKind.Sequential)]
    public struct SHFILEINFO
    {
        public IntPtr hIcon;
        public IntPtr iIcon;
        public uint dwAttributes;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
        public string szDisplayName;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
        public string szTypeName;
    };

    public class Win32ApiNativeMethods
    {
        public const uint SHGFI_ICON = 0x100;
        public const uint SHGFI_LARGEICON = 0x0;
        public const uint SHGFI_SMALLICON = 0x1;

        [DllImport("shell32.dll")]
        public static extern IntPtr SHGetFileInfo(string pszPath,
                                    uint dwFileAttributes,
                                    ref SHFILEINFO psfi,
                                    uint cbSizeFileInfo,
                                    uint uFlags);

        public static ImageSource GetIcon(string fileName)
        {
            SHFILEINFO shfileinfo = new SHFILEINFO();
            IntPtr handle = SHGetFileInfo(fileName, 0, ref  shfileinfo,
                                     (uint)Marshal.SizeOf(shfileinfo),
                                      SHGFI_ICON |
                                      SHGFI_SMALLICON);
            ImageSource imageSource = null;
            if (handle != IntPtr.Zero && shfileinfo.hIcon != null)
                imageSource = Imaging.CreateBitmapSourceFromHIcon(shfileinfo.hIcon, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
            
            return imageSource;
        }
    }


}
